<template>
    <div id="app">
      <!-- 图片上传区域 -->
      <div class="upload-container">
        <input type="file" multiple accept="image/*" @change="handleImageUpload" />
        <button @click="saveAsImage">保存为图片</button>
      </div>
  
      <!-- 图片和箭头/文字容器 -->
      <div class="image-container" ref="imageContainer">
        <div
          v-for="(image, index) in images"
          :key="index"
          class="image-wrapper"
          :style="{ top: image.top + 'px', left: image.left + 'px', width: image.width + 'px', height: image.height + 'px' }"
          @mousedown="startImageDrag(index, $event)"
        >
          <img :src="image.src" alt="uploaded image" class="uploaded-image" />

           <!-- 删除按钮 -->
          <button @click="deleteImage(index)" class="delete-button">删除</button>
  
          <!-- 图片上的箭头和文字 -->
          <div
            v-for="(item, idx) in image.items"
            :key="idx"
            class="draggable-resizable"
            :style="{ top: item.top + 'px', left: item.left + 'px', width: item.width + 'px', height: item.height + 'px' }"
            @mousedown="startTextDrag(index, idx, $event)"
          >
            <div class="resize-handle" @mousedown="startTextResize(index, idx, $event)"  ></div>
            <div class="arrow-text">
              <div class="arrow" 
              :style="{transform: 'scale(' + item.scale + ') rotate(' + item.rotation + 'deg)' }"
              :class="{ selected: scaling &&  scalingIndex.imageIndex === index}"
              @click="rotateTriangle(index, idx, $event)" 
              ></div>
              <input v-model="item.text" type="text" :style="{ fontSize: item.fontSize + 'px',width: item.width + 'px', height: item.height + 'px' }"
               class="text-input" placeholder="Edit text" 
               :data-id="item.id"
               />
            </div>
          </div>
          
          <!-- 图片缩放手柄 -->
          <div class="resize-handle-image" @mousedown="startImageResize(index, $event)"></div>
        </div>
      </div>
      <img v-if="savedImage" :src="savedImage" alt="Saved Image" class="saved-image" />
    </div>
  </template>
  
  <script>
  
  import html2canvas from "html2canvas";
  
  export default {
    data() {
      return {
        images: [],
        dragging: false,
        textDragging: false,
        resizing: false,
        imageResizing: false,
        dragIndex: null, // For image dragging
        dragTextIndex: null, // For text dragging
        dragOffsetX: 0,
        dragOffsetY: 0,
        resizeIndex: null,
        resizeOffsetX: 0,
        resizeOffsetY: 0,
        textResizeIndex: null,
        textResizeOffsetX: 0,
        textResizeOffsetY: 0,

        savedImage: null,
        savedElements: [], // 用于保存图片和文本元素的数据
        scaling: false,  // 是否正在缩放
        scalingIndex: null,  // 被缩放的三角形索引
        scalingStartX: 0,  // 缩放开始时的鼠标位置
        scalingStartY: 0,  // 缩放开始时的鼠标位置
      };
    },
    created() {
         // 从localStorage中加载已保存的数据
        this.savedImage = localStorage.getItem('savedImage');
        this.images = JSON.parse(localStorage.getItem('savedElements')) || [];    
    },
    methods: {
      // 处理图片上传
      handleImageUpload(event) {
        const files = event.target.files;
        Array.from(files).forEach((file) => {
          const reader = new FileReader();
          reader.onload = (e) => {
            this.images.push({
              src: e.target.result,
              top: 50,
              left: 50,
              width: 200,
              height: 150,
              items: [
                {
                  id: Date.now(), // 唯一ID
                  left: 20,
                  top: 20,
                  width: 100,
                  height: 50,
                  text: '文字内容',
                  fontSize: 14,
                  scale: 1, // 默认缩放比例
                  rotation: 0, // 默认旋转角度
                }
              ]
            });
          };
          reader.readAsDataURL(file);
        });
      },
  
      // 开始拖拽图片
      startImageDrag(index, event) {
        this.dragging = true;
        this.dragIndex = index;
        this.dragOffsetX = event.clientX - this.images[index].left;
        this.dragOffsetY = event.clientY - this.images[index].top;
        document.addEventListener("mousemove", this.onImageDrag);
        document.addEventListener("mouseup", this.stopImageDrag);
      },
  
      // 拖拽图片
      onImageDrag(event) {
        if (this.dragging && this.dragIndex !== null) {
          this.images[this.dragIndex].left = event.clientX - this.dragOffsetX;
          this.images[this.dragIndex].top = event.clientY - this.dragOffsetY;
        }
      },
  
      // 停止拖拽图片
      stopImageDrag() {
        this.dragging = false;
        this.dragIndex = null;
        document.removeEventListener("mousemove", this.onImageDrag);
        document.removeEventListener("mouseup", this.stopImageDrag);
      },
  
      // 开始调整图片大小
      startImageResize(index, event) {
        this.imageResizing = true;
        this.resizeIndex = index;
        this.resizeOffsetX = event.clientX;
        this.resizeOffsetY = event.clientY;
        document.addEventListener("mousemove", this.onImageResize);
        document.addEventListener("mouseup", this.stopImageResize);
      },
  
      // 调整图片大小
      onImageResize(event) {
        if (this.imageResizing && this.resizeIndex !== null) {
          const deltaX = event.clientX - this.resizeOffsetX;
          const deltaY = event.clientY - this.resizeOffsetY;
  
          this.images[this.resizeIndex].width += deltaX;
          this.images[this.resizeIndex].height += deltaY;
  
          this.resizeOffsetX = event.clientX;
          this.resizeOffsetY = event.clientY;
        }
      },
  
      // 停止调整图片大小
      stopImageResize() {
        this.imageResizing = false;
        this.resizeIndex = null;
        document.removeEventListener("mousemove", this.onImageResize);
        document.removeEventListener("mouseup", this.stopImageResize);
      },
  
      // 开始拖拽文字和箭头
      startTextDrag(imageIndex, textIndex, event) {
        event.stopPropagation(); // 阻止事件冒泡
        this.textDragging = true;
        this.dragTextIndex = { imageIndex, textIndex };
        this.dragOffsetX = event.clientX - this.images[imageIndex].items[textIndex].left;
        this.dragOffsetY = event.clientY - this.images[imageIndex].items[textIndex].top;
        document.addEventListener("mousemove", this.onTextDrag);
        document.addEventListener("mouseup", this.stopTextDrag);
      },
  
      // 拖拽文字和箭头
      onTextDrag(event) {
        if (this.textDragging && this.dragTextIndex) {
          const image = this.images[this.dragTextIndex.imageIndex];
          const item = image.items[this.dragTextIndex.textIndex];
          item.left = event.clientX - this.dragOffsetX;
          item.top = event.clientY - this.dragOffsetY;
        }
      },
  
      // 停止拖拽文字和箭头
      stopTextDrag() {
        this.textDragging = false;
        this.dragTextIndex = null;
        document.removeEventListener("mousemove", this.onTextDrag);
        document.removeEventListener("mouseup", this.stopTextDrag);
      },
  
      // 开始调整文字大小
      startTextResize(imageIndex, textIndex, event) {
        event.stopPropagation(); // 阻止事件冒泡
        this.textResizing = true;
        this.textResizeIndex = { imageIndex, textIndex };
        this.textResizeOffsetX = event.clientX;
        this.textResizeOffsetY = event.clientY;
        document.addEventListener("mousemove", this.onTextResize);
        document.addEventListener("mouseup", this.stopTextResize);
      },
  
      // 调整文字大小
      onTextResize(event) {
        if (this.textResizing && this.textResizeIndex !== null) {
          const image = this.images[this.textResizeIndex.imageIndex];
          const item = image.items[this.textResizeIndex.textIndex];
          const deltaX = event.clientX - this.textResizeOffsetX;
          const deltaY = event.clientY - this.textResizeOffsetY;
  
          item.width += deltaX;
          item.height += deltaY;

           // 动态调整字体大小
        const newFontSize = item.height / 2; // 字体大小范围 10px 到 30px
        this.$set(item, 'fontSize', newFontSize); // 更新字体大小

          this.textResizeOffsetX = event.clientX;
          this.textResizeOffsetY = event.clientY;
        }
      },
  
      // 停止调整文字大小
      stopTextResize() {
        this.textResizing = false;
        this.textResizeIndex = null;
        document.removeEventListener("mousemove", this.onTextResize);
        document.removeEventListener("mouseup", this.stopTextResize);
      },

      // 点击三角形进行旋转
      rotateTriangle(imageIndex, itemIndex, event) {
        const item = this.images[imageIndex].items[itemIndex];
        // 每次点击增加 45 度的旋转
        item.rotation = (item.rotation + 45) % 360; // 保证旋转角度在 0 到 360 之间
        this.scaling = true;
        this.scalingIndex = { imageIndex, itemIndex };
        this.scalingStartX = event.clientX;
        this.scalingStartY = event.clientY;
        console.log(this.scalingIndex)
        // 禁用文本输入框的聚焦，避免干扰
        event.stopPropagation();

       // 开始监听滚动事件
        document.addEventListener("wheel", this.onWheelScroll, { passive: false });
        document.addEventListener("mouseup", this.stopScaling);
      },

      // 处理滚轮事件来调整缩放
    onWheelScroll(event) {
      if (this.scaling && this.scalingIndex !== null) {
        const { imageIndex, itemIndex } = this.scalingIndex;
        const item = this.images[imageIndex].items[itemIndex];

        // 根据滚动方向来调整缩放比例，deltaY 表示滚动的方向
        const delta = event.deltaY > 0 ? -0.05 : 0.05; // 向下滚动为负，向上滚动为正
        const newScale = item.scale + delta;

        // 限制缩放比例的范围
        item.scale = Math.max(0.1, Math.min(3, newScale)); // 最小为0.1，最大为3

        event.preventDefault(); // 阻止默认的滚动行为
      }
    },

      // 停止缩放
      stopScaling() {
        this.scaling = false;
        this.scalingIndex = null;
        document.removeEventListener("mouseup", this.stopScaling);
        document.removeEventListener("wheel", this.onWheelScroll);
      },

      // 保存为图片并保存元素数据
      saveAsImage() {
        const container = this.$refs.imageContainer;

         // 移除所有 resize-handle-image 元素
        this.removeResizeHandles();

         // 替换所有 input 为 div
        this.replaceInputsWithDivs();
        
        html2canvas(container,{useCORS: true,}).then((canvas) => {
            const base64Image = canvas.toDataURL('image/png');
            this.savedImage = base64Image;
           
            // 保存所有图片和元素的状态
            this.savedElements = this.images.map(image => ({
                src: image.src,
                top: image.top,
                left: image.left,
                width: image.width,
                height: image.height,
                items: image.items.map(item => ({
                        id: item.id,
                        text: item.text,
                        top: item.top,
                        left: item.left,
                        width: item.width,
                        height: item.height,
                        fontSize: item.fontSize,
                        scale: item.scale, // 默认缩放比例
                        rotation: item.rotation, // 默认旋转角度
                    }))
            }));
            localStorage.setItem('savedImage', base64Image);
            localStorage.setItem('savedElements', JSON.stringify(this.savedElements));
            
            alert("图片已保存!");
            // 还原 div 为 input
            this.restoreDivsToInputs();
        });
      },

      // 加载保存的图片和元素数据
      replaceInputsWithDivs() {
        this.images.forEach((image) => {
            image.items.forEach((item) => {
                const inputElement = document.querySelector(`input[data-id='${item.id}']`);
                if (inputElement) {
                    const div = document.createElement('div');
                    div.textContent = item.text;
                    div.style.cssText = inputElement.style.cssText;
                    // 确保字体颜色被保留
                    div.style.color = item.color || '#000';  // 如果没有设置颜色，默认黑色
                    div.style.whiteSpace = 'nowrap';
                    div.style.overflow = 'hidden';
                    div.className = 'text-input';
                    div.setAttribute('data-id', item.id);
                    inputElement.replaceWith(div);
                }
                });
            });
        },

        // 恢复输入框
        restoreDivsToInputs() {
            this.images.forEach((image) => {
                image.items.forEach((item) => {
                const divElement = document.querySelector(`div[data-id='${item.id}']`);
                if (divElement) {
                    const input = document.createElement('input');
                    input.value = item.text;
                    input.type = 'text';
                    input.style.cssText = divElement.style.cssText;
                    input.className = 'text-input';
                    input.setAttribute('data-id', item.id);
                    divElement.replaceWith(input);
                }
                });
            });
        },
        // 移除所有 resize-handle-image 元素
        removeResizeHandles() {
            const resizeHandles = document.querySelectorAll('.resize-handle-image');
            const resizeHandle = document.querySelectorAll('.resize-handle');
            const deleteButton = document.querySelectorAll('.delete-button');

            resizeHandles.forEach((handle) => handle.remove());
            resizeHandle.forEach((handle) => handle.remove());
            deleteButton.forEach((button) => button.remove());
        },

          // 删除图片
        deleteImage(index) {
            if (confirm("确定要删除这张图片吗？")) {
            // 从 images 数组中删除图片
            this.images.splice(index, 1);
            
            // 删除本地存储中的数据
            this.updateLocalStorage();
            }
        },

        // 更新本地存储中的数据
        updateLocalStorage() {
            localStorage.setItem('savedElements', JSON.stringify(this.images));
            // 如果需要，可以更新保存的图片
            html2canvas(this.$refs.imageContainer, { useCORS: true }).then((canvas) => {
            const base64Image = canvas.toDataURL('image/png');
            localStorage.setItem('savedImage', base64Image);
            });
        }

    }
  };
  </script>
  
  <style scoped>
  .upload-container {
    margin: 20px;
  }
  
  .image-container {
    position: relative;
    width: 100%;
    height: 500px;  /* 确保高度有值 */
    border: 1px solid #ccc;  /* 可视化边框，方便调试 */
    background-color: #fff;  /* 设置背景颜色以便可见 */
    overflow: hidden;
}
  
  .image-wrapper {
    position: absolute;
    cursor: pointer;
    border: 2px solid rgba(0, 0, 0, 0.2);
  }
  
  .uploaded-image {
    width: 100%;
    height: 100%;
  }
  
  .draggable-resizable {
    position: absolute;
    cursor: move;
  }
  
  .arrow-text {
    position: relative;
    background-color: rgba(255, 255, 255, 0.7);
    padding: 5px;
    border-radius: 5px;
  }
  
  .arrow {
    width: 0;
    height: 0;
    border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    border-bottom: 20px solid black;
    position: absolute;
    top: -20px;
    left: 50%;
    transform: translateX(-50%);
  }
  .text-content {
    font-size: 14px;
    color: black;
    background-color: transparent;
    padding: 5px;
    border: 1px solid transparent;
  }
  
  .text-input {
    color: black;
    font-size: 14px;
    background: transparent; /* 避免背景色影响渲染 */
    border: none;
    height: 20px;
    width: auto;
  }
  
  .resize-handle {
    position: absolute;
    bottom: 5px;
    right: 5px;
    width: 10px;
    height: 10px;
    background-color: black;
    cursor: se-resize;
    z-index: 6000;
  }
  
  .resize-handle-image {
    position: absolute;
    bottom: 5px;
    right: 5px;
    width: 15px;
    height: 15px;
    background-color: black;
    cursor: se-resize;
  }
/* 定义闪烁动画 */
@keyframes blink {
  0% {
    box-shadow: 0 0 8px 2px rgba(255, 0, 0, 0.7);
  }
  50% {
    box-shadow: 0 0 8px 2px rgba(255, 0, 0, 0.2);
  }
  100% {
    box-shadow: 0 0 8px 2px rgba(255, 0, 0, 0.7);
  }
}

/* 选中状态样式 */
.arrow-text .selected {
  animation: blink 1s infinite; /* 应用闪烁动画，1秒周期，无限循环 */
  transition: box-shadow 0.2s ease;
}

.delete-button {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: red;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  font-size: 14px;
  border-radius: 5px;
  z-index: 100;
}

.delete-button:hover {
  background-color: darkred;
}
  </style>
  